<template>
    <transition-group class="message" tag="div">
        <div class="message-content" v-for="message in messages" :key="message.id">
            {{ message.content }}
        </div>
    </transition-group>
</template>

<script>
import { ref, unref } from 'vue'
export default {
  name: 'Message',
  setup (props, { expose }) {
    // 消息列表
    const messages = ref([])
     
    let id = 0

    const uuid = () => `message_${id++}`
    
    const add = (message) => {
      const id = uuid()
      const _message = {
        ...message,
        id
      }
      unref(messages).push(_message)
      const { duration = 3 } =  message

      const timer = setTimeout(() => {
        clearTimeout(timer)
        remove(id)
      }, duration * 1000)
    }
     
    const remove = (id) => {
      messages.value = unref(messages).filter(message => message.id !== id)
    }
     
    expose({
      add
    })
     
    return {
      messages
    }
  }
}
</script>
<style scoped>
.message {
    position: fixed;
    z-index: 999;
    top: 1rem;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
    padding: 0 2rem;
}

.message-content {
    width: 100%;
    padding: 12px 16px;
    border-radius: 0.3rem;
    box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
    background: #3f3e3e;
    margin-bottom: 20px;
    color: #fff;
}

.v-enter-active,
.v-leave-active {
    transition: all .5s ease-in;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
    transform: translateY(-100%);
}

</style>